package com.tudouji.project.quality.service.impl;

import com.tudouji.common.utils.DateUtils;
import com.tudouji.common.utils.IdUtils;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.project.harvest.domain.Forderstandard;
import com.tudouji.project.harvest.domain.Freightorder;
import com.tudouji.project.harvest.domain.Procurementcontract;
import com.tudouji.project.harvest.domain.Qaform;
import com.tudouji.project.harvest.mapper.ForderstandardMapper;
import com.tudouji.project.harvest.mapper.FreightorderMapper;
import com.tudouji.project.harvest.mapper.ProcurementcontractMapper;
import com.tudouji.project.harvest.mapper.QaformMapper;
import com.tudouji.project.quality.domain.Qaitems;
import com.tudouji.project.quality.domain.Qamain;
import com.tudouji.project.quality.domain.Qarecord;
import com.tudouji.project.quality.domain.Qastandard;
import com.tudouji.project.quality.mapper.QaitemsMapper;
import com.tudouji.project.quality.mapper.QamainMapper;
import com.tudouji.project.quality.mapper.QarecordMapper;
import com.tudouji.project.quality.mapper.QastandardMapper;
import com.tudouji.project.quality.service.IQarecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 质检记录Service业务层处理
 *
 * @author tudouji
 * @date 2022-11-01
 */
@Slf4j
@Service
public class QarecordServiceImpl implements IQarecordService {
    @Autowired
    private QarecordMapper qarecordMapper;
    @Autowired
    private QaformMapper qaformMapper;
    @Autowired
    private QamainMapper qamainMapper;
    @Autowired
    private QastandardMapper qastandardMapper;
    @Autowired
    private QaitemsMapper qaitemsMapper;
    @Autowired
    private ProcurementcontractMapper procurementcontractMapper;
    @Autowired
    private ForderstandardMapper forderstandardMapper;
    @Autowired
    private QarecordServiceImpl qarecordService;
    @Autowired
    private FreightorderMapper freightorderMapper;

    /**
     * 查询质检记录
     *
     * @param guid 质检记录ID
     * @return 质检记录
     */
    @Override
    public Qarecord selectQarecordById(String guid) {
        return qarecordMapper.selectQarecordById(guid);
    }

    /**
     * 查询质检记录列表
     *
     * @param qarecord 质检记录
     * @return 质检记录
     */
    @Override
    public List<Qarecord> selectQarecordList(Qarecord qarecord) {
        return qarecordMapper.selectQarecordList(qarecord);
    }

    @Override
    public List<Qarecord> selectQarecordListByFoguid(String foguid) {
        return qarecordMapper.selectQarecordListByFoguid(foguid);
    }

    /**
     * 新增质检记录
     *
     * @param qarecord 质检记录
     * @return 结果
     */
    @Override
    public int insertQarecord(Qarecord qarecord) {
        return qarecordMapper.insertQarecord(qarecord);
    }

    /**
     * 修改质检记录
     *
     * @param qarecord 质检记录
     * @return 结果
     */
    @Override
    public int updateQarecord(Qarecord qarecord) {
        return qarecordMapper.updateQarecord(qarecord);
    }

    /**
     * 批量删除质检记录
     *
     * @param guids 需要删除的质检记录ID
     * @return 结果
     */
    @Override
    public int deleteQarecordByIds(String[] guids) {
        return qarecordMapper.deleteQarecordByIds(guids);
    }

    /**
     * 删除质检记录信息
     *
     * @param guid 质检记录ID
     * @return 结果
     */
    @Override
    public int deleteQarecordById(String guid) {
        return qarecordMapper.deleteQarecordById(guid);
    }

    @Override
    public AjaxResult getQaRecord(String guid) {
        AjaxResult result = AjaxResult.success();
        Qarecord record = qarecordMapper.selectQarecordById(guid);
        Freightorder order = freightorderMapper.selectFreightorderById(record.getFoguid());
        List<Qaitems> qaitems = qarecordService.getQaItemsMain(order);
        result.put("record", record);
        result.put("order", order);
        result.put("qaitems", qaitems);
        return result;
    }

    /**
     * @return 查询质检：质检项信息扩展：
     * 1、适用原料薯系列（I/II/III/IV/V，ALL-全部适用，字典）
     * 2、适用区域（S区域、N区域等，ALL-全部适用，字典）
     * @Author shaodong
     * @Description 查找质检相修改为从合同中查找
     * @Date 10:00 2020/9/11
     * @Param
     **/
    public List<Qaitems> getQaItemsMain(Freightorder order) {
        List<Qaitems> qaitems = new ArrayList<>();
        if (StringUtils.isNotBlank(order.getContractid())) {
            if (order.getIsdiscount() == 1 || order.getIsdiscount() == 2 ||order.getIsdiscount() == 3) {
                Integer[] type = new Integer[]{2};
                /*2022.03.01  淀粉标准的，然后把type=4加上*/
                Procurementcontract contract = procurementcontractMapper.selectProcurementcontractById(order.getContractid());
                Qamain qamain = qamainMapper.selectQamainById(contract.getQamainid());
                if (2 == qamain.getType()) {
                    type = new Integer[]{2, 4};
                }
                qaitems = getQaItemsByContract(type, order.getContractid());
            } else if (order.getIsdiscount() == 5) {
                Integer[] type = new Integer[]{2};
                qaitems = getQaItemsByContract(type, order.getContractid());
            } else if (order.getIsdiscount() == 6) {
                Integer[] type = new Integer[]{};
                qaitems = getQaItemsByContract(type, order.getContractid());
            }
            if (qaitems.size() > 0) {
                return qaitems;
            }
        }
        return qaitems;
    }

    /**
     * @return
     * @Author shaodong
     * @Description 通过合同查询质检标准，并查询
     * @Date 11:14 2020/9/11
     * @Param
     **/
    private List<Qaitems> getQaItemsByContract(Integer[] types, String contractid) {
        Procurementcontract contract = procurementcontractMapper.selectProcurementcontractById(contractid);

        if (null != contract) {
            if (StringUtils.isBlank(contract.getQamainid())) {
                return new ArrayList<>();
            } else {
                Qastandard qd = new Qastandard();
                if (types.length > 0) {
                    qd.setTypes(types);
                }
                List<Qastandard> qds = qastandardMapper.selectQastandardList(qd);
                String[] qdguids = new String[qds.size()];
                for (int i = 0; i < qds.size(); i++) {
                    qdguids[i] = qds.get(i).getGuid();
                }
                Qaitems item = new Qaitems();
                item.setQamainguid(contract.getQamainid());
                item.setQastandards(qdguids);
                if (contract.getSeries() == null) {
                    contract.setSeries(1);
                    contract.setRegion(1);
                }
                if (contract.getRegion() == null) {
                    contract.setSeries(1);
                    contract.setRegion(1);
                }
                item.setRawpotatos(contract.getSeries());
                item.setArea(contract.getRegion());
                item.setStatus(0);
                return qaitemsMapper.getQaItemsByContract(item);
            }
        } else {
            return new ArrayList<>();
        }
    }

    public Qarecord findItemSum(String orderguid) {
        return this.qarecordMapper.findItemSum(orderguid);
    }

    public void addOrUpdate(Qarecord qarecord) {
        if (StringUtils.isEmpty(qarecord.getGuid())) {
            qarecord.setCreatedate(DateUtils.getNowDate());
            qarecord.setGuid(IdUtils.fastSimpleUUID());
            this.insertQarecord(qarecord);
        } else {
            qarecord.setLastupdate(DateUtils.getNowDate());
            this.updateQarecord(qarecord);
        }
    }


    /**
     * 更新质检单(必须在插入记录之后)
     *
     * @param orderguid 货运单ID
     */
    public void updateQAform(String orderguid) {
        Qaform qaform = qaformMapper.selectQaformByFoguid(orderguid);
        Qarecord qarecord = qarecordMapper.findSum(orderguid);

        log.info(qarecord.toString());
        Integer pknumssum = qarecord.getPknumssum();
        BigDecimal totalweightsum = qarecord.getTotalweightsum();
        BigDecimal okweightsum = qarecord.getOkweightsum();
        BigDecimal notokweightsum = qarecord.getNotokweightsum();
        BigDecimal soilchkweight = qarecord.getSoilchkweight();
        BigDecimal unqualifiedchkweight = qarecord.getUnqualifiedchkweight();
        BigDecimal dedculate = BigDecimal.ZERO;
        BigDecimal dedculateSoil = BigDecimal.ZERO;
        BigDecimal dedculateUnqualified = BigDecimal.ZERO;
        if (totalweightsum == null) {
            totalweightsum = BigDecimal.ZERO;
        }
        if (okweightsum == null) {
            okweightsum = BigDecimal.ZERO;
        }
        if (notokweightsum == null) {
            notokweightsum = BigDecimal.ZERO;
        } else {
            dedculate = qarecord.getNotokweightsum().divide(qarecord.getTotalweightsum(), 4, BigDecimal.ROUND_HALF_UP);
        }
        if (soilchkweight == null) {
            soilchkweight = BigDecimal.ZERO;
        } else {
            dedculateSoil = qarecord.getSoilchkweight().divide(qarecord.getTotalweightsum(), 4, BigDecimal.ROUND_HALF_UP);
        }
        if (unqualifiedchkweight == null) {
            unqualifiedchkweight = BigDecimal.ZERO;
        } else {
            dedculateUnqualified = qarecord.getUnqualifiedchkweight().divide(qarecord.getTotalweightsum(), 4, BigDecimal.ROUND_HALF_UP);
        }
        qaform.setChkpknum(pknumssum);
        qaform.setChkwght(totalweightsum);
        qaform.setOkweight(okweightsum);
        qaform.setSoilchkweight(soilchkweight);
        qaform.setSoilchkrate(dedculateSoil.multiply(new BigDecimal(100)));
        qaform.setUnqualifiedchkweight(unqualifiedchkweight);
        qaform.setUnqualifiedchkrate(dedculateUnqualified.multiply(new BigDecimal(100)));
        qaform.setNotokweight(notokweightsum);
        qaform.setDeductrate(dedculate.multiply(new BigDecimal(100)));
        qaform.setLastupdate(new Date());
        qaformMapper.updateQaform(qaform);
    }


    /**
     * @return
     * @auther shaodong
     * @desc 创建扣杂标准表
     * 前提是isdiscount==4,通过质检相的扣杂类型，从质检记录中合并重量，计算出百分比，更新到货运单扣杂标准子表
     * @Date 16:46 2020/8/25
     * @Param 扣杂标准GUIDS
     * @Param 合同id
     * @Param 货运单id
     * <p>
     * select * from forderstandard left join qaitems
     **/
    public void addForderStandard(Freightorder order) {
        List<Qaitems> qaitems = this.getQaItemsMain(order);
        Qarecord qarecord = qarecordMapper.findItemSum(order.getGuid());
        List<Forderstandard> forderstandards = forderstandardMapper.selectForderstandardListByForderid(order.getGuid());

        ArrayList<BigDecimal> standardValue = new ArrayList<>();
        for (int i = 0; i < forderstandards.size(); i++) {
            BigDecimal value = BigDecimal.ZERO;
            Qastandard qA = qastandardMapper.selectQastandardById(forderstandards.get(i).getStandardid());
            //土杂划入不计价标准:前提是只能有一个不计价标准
            if (qA.getIsvaluation() == 2) {
                value = value.add(qarecord.getSoilchkweight());
            }
            for (int j = 0; j < qaitems.size(); j++) {
                if (forderstandards.get(i).getStandardid().equalsIgnoreCase(qaitems.get(j).getQastandard())) {

                    if (0 == j) {
                        value = value.add(qarecord.getItem1weight());
                    }
                    if (1 == j) {
                        value = value.add(qarecord.getItem2weight());
                    }
                    if (2 == j) {
                        value = value.add(qarecord.getItem3weight());
                    }
                    if (3 == j) {
                        value = value.add(qarecord.getItem4weight());
                    }
                    if (4 == j) {
                        value = value.add(qarecord.getItem5weight());
                    }
                    if (5 == j) {
                        value = value.add(qarecord.getItem6weight());
                    }
                    if (6 == j) {
                        value = value.add(qarecord.getItem7weight());
                    }
                    if (7 == j) {
                        value = value.add(qarecord.getItem8weight());
                    }
                    if (8 == j) {
                        value = value.add(qarecord.getItem9weight());
                    }
                    if (9 == j) {
                        value = value.add(qarecord.getItem10weight());
                    }
                    if (10 == j) {
                        value = value.add(qarecord.getItem11weight());
                    }
                    if (11 == j) {
                        value = value.add(qarecord.getItem12weight());
                    }
                    if (12 == j) {
                        value = value.add(qarecord.getItem13weight());
                    }
                    if (13 == j) {
                        value = value.add(qarecord.getItem14weight());
                    }
                    if (14 == j) {
                        value = value.add(qarecord.getItem15weight());
                    }
                    if (15 == j) {
                        value = value.add(qarecord.getItem16weight());
                    }
                    if (16 == j) {
                        value = value.add(qarecord.getItem17weight());
                    }
                    if (17 == j) {
                        value = value.add(qarecord.getItem18weight());
                    }
                    if (18 == j) {
                        value = value.add(qarecord.getItem19weight());
                    }
                    if (19 == j) {
                        value = value.add(qarecord.getItem20weight());
                    }

                }
            }
            standardValue.add(value);
            if (i == (forderstandards.size() - 1)) {
                for (int j = 0; j < standardValue.size(); j++) {
                    BigDecimal qaresult = standardValue.get(j).divide(qarecord.getTotalweightsum(), 4, BigDecimal.ROUND_HALF_UP);
                    Forderstandard fs = forderstandards.get(j);
                    fs.setQaresult(qaresult);
                    forderstandardMapper.updateForderstandard(fs);
                }
            }
        }

    }
}
